package com.pmcc.miniProgram.web;


import com.google.gson.Gson;


import com.pmcc.miniProgram.vo.CodeExchangeOpenid;
import com.pmcc.platform.shopping.entity.Shopping;
import com.pmcc.platform.shopping.entity.ShoppingApply;
import com.pmcc.platform.shopping.repository.ShoppingApplyRepository;
import com.pmcc.platform.shopping.repository.ShoppingRepository;
import com.pmcc.platform.shopping.service.ShoppingService;
import com.pmcc.platform.user.entity.MinShoppingUserInfo;
import com.pmcc.platform.user.repository.MinShoppingUserInfoRepository;
import com.pmcc.utils.AntPage;
import com.pmcc.utils.ApiResultBean;
import com.pmcc.utils.StringUtil;
import com.pmcc.utils.UUIDGenerator;
import com.pmcc.utils.wechat.HttpClientUtil;
import com.pmcc.utils.wechat.WXBizDataCrypt;
import com.pmcc.utils.wechat.WechatMiniConfig;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/miniProgram/shopping")
public class MiniShoppingController {


    @Autowired
    MinShoppingUserInfoRepository minUserInfoRepository;

    @Autowired
    ShoppingRepository shoppingRepository;

    @Autowired
    ShoppingService shoppingService;

    @Autowired
    ShoppingApplyRepository shoppingApplyRepository;

    /**
     * 用户生成code
     *
     * @return
     */
    public String createCode() {
        String userCode = UUIDGenerator.generateShortUuid();
        List<MinShoppingUserInfo> code = minUserInfoRepository.findAllByCode(userCode);
        if (code != null && code.size() > 0) {
            return createCode();
        } else {
            return userCode;
        }
    }

    /**
     * 登录凭证校验(微信小程序)
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "getOpenid", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean getOpenid(String code) {
        ApiResultBean apiResultBean = new ApiResultBean();
        //根据code换取对应的openid和session_key
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WechatMiniConfig.MINI_APP_ID + "&secret=" + WechatMiniConfig.MINI_APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        // String tokenUrl
        String jsonStr = HttpClientUtil.httpGetRequest(url);

        Gson gson = new Gson();

        CodeExchangeOpenid codeExchangeOpenid = gson.fromJson(jsonStr, CodeExchangeOpenid.class);

        if (StringUtil.isEmpty(codeExchangeOpenid.getErrcode())) {

            if (StringUtils.isNotEmpty(codeExchangeOpenid.getOpenid())) {
                //去小程序user表查询是否存在
                String openid = codeExchangeOpenid.getOpenid();
                List<MinShoppingUserInfo> minUserInfos = minUserInfoRepository.findAllByOpenIdAndDelFlag(openid, "0");
                if (minUserInfos.size() > 0) {


                    //查询是否关联
                    List<Shopping> shoppings = shoppingRepository.findAllByMiniUserIdAndDelFlag(minUserInfos.get(0).getId(), "0");
                    //关联的有直接将导购的id返回去
                    if (shoppings.size() > 0) {
                        minUserInfos.get(0).setIsLog("0");
                        minUserInfos.get(0).setIsApplication("0");
                        minUserInfos.get(0).setShoppingId(shoppings.get(0).getId());
                        apiResultBean.setCode(ApiResultBean.SUCCESS);
                        apiResultBean.setData(minUserInfos.get(0));
                        return apiResultBean;
                        //无关联，通过手机号验证=
                    } else {

                        List<ShoppingApply> shoppingApplies = shoppingApplyRepository.findAllByMiniUserIdAndIsApplyAndDelFlag(minUserInfos.get(0).getId(), "1", "0");
                        if (shoppingApplies.size() > 0) {
                            minUserInfos.get(0).setIsApplication("2");
                        } else {
                            minUserInfos.get(0).setIsApplication("1");
                        }
                        if (StringUtil.isEmpty(minUserInfos.get(0).getPhone())) {
                            minUserInfos.get(0).setIsLog("1");
                        } else {
                            minUserInfos.get(0).setIsLog("0");
                        }


                        minUserInfos.get(0).setSessionKey(codeExchangeOpenid.getSession_key());
                        apiResultBean.setCode(ApiResultBean.SUCCESS);
                        apiResultBean.setData(minUserInfos.get(0));
                        return apiResultBean;
                    }


                    //小程序user不存在
                } else {


                    MinShoppingUserInfo minUserInfo = new MinShoppingUserInfo();
                    minUserInfo.setOpenId(openid);
                    minUserInfo.setCode(createCode());
                    minUserInfo.setIsLog("1");
                    minUserInfo.setSessionKey(codeExchangeOpenid.getSession_key());
                    minUserInfoRepository.saveAndFlush(minUserInfo);
                    apiResultBean.setData(minUserInfo);
                    apiResultBean.setCode(ApiResultBean.SUCCESS);
                }

            } else {
                //处理错误信息
                CodeExchangeOpenid.handleError(codeExchangeOpenid, apiResultBean);
                return apiResultBean;
            }


        }
        return apiResultBean;
    }

    /**
     * 获取unionId,并保存用户信息
     *
     * @param
     * @return
     *//*
    @RequestMapping(value = "saveUserPhone", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean saveUserPhone(String openid, String sessionKey, String encryptedData, String iv) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if (StringUtil.isEmpty(openid) || StringUtil.isEmpty(encryptedData) || StringUtil.isEmpty(sessionKey) || StringUtil.isEmpty(sessionKey)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("请求失败！openid为空！");
            return apiResultBean;
        }

        WXBizDataCrypt biz = new WXBizDataCrypt(WechatMiniConfig.MINI_APP_ID, sessionKey);
        String returnInfo = biz.decryptData(encryptedData, iv);
        JSONObject jsonObject = JSONObject.fromObject(returnInfo);

        //获取公共配置
        if (("succeed").equals(jsonObject.get("msg"))) {
            JSONObject object = JSONObject.fromObject(jsonObject.get("userInfo"));
            //如果没有unionId，就用openId查询
            List<MinShoppingUserInfo> minUserInfos = minUserInfoRepository.findAllByOpenIdAndDelFlag(openid,"0");
            if (object.get("phoneNumber") != null) {
                minUserInfos.get(0).setPhone(object.get("phoneNumber").toString());
                //如果保存手机号，并且推荐人信息不为空，增加推荐记录
            }
            //处理最后浏览店铺
            minUserInfos.get(0).setModifyTime(new Date());
           minUserInfoRepository.saveAndFlush(minUserInfos.get(0));
            apiResultBean.setCode(ApiResultBean.SUCCESS);
            apiResultBean.setMsg("保存成功");
            apiResultBean.setData(minUserInfos.get(0));
        } else {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("保存失败");
        }
        return apiResultBean;
    }
*/
    @RequestMapping(value = "saveUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean saveUserInfo(String miniUserId, String sessionKey, String encryptedData, String iv) {
        ApiResultBean apiResultBean = new ApiResultBean();

        if (StringUtil.isEmpty(miniUserId) || StringUtil.isEmpty(encryptedData) || StringUtil.isEmpty(sessionKey) || StringUtil.isEmpty(iv)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("请求失败！miniUserId为空！");
            return apiResultBean;
        }

        WXBizDataCrypt biz = new WXBizDataCrypt(WechatMiniConfig.MINI_APP_ID, sessionKey);
        String returnInfo = biz.decryptData(encryptedData, iv);
        JSONObject object = JSONObject.fromObject(returnInfo);
        String userinfo = object.get("userInfo").toString();
        JSONObject jsonObject = JSONObject.fromObject(userinfo);

        //获取公共配置
        //如果没有unionId，就用openId查询
        MinShoppingUserInfo minUserInfo = minUserInfoRepository.findOne(miniUserId);


        if (jsonObject.get("nickName") != null) {
            String aa = this.filterEmoji(jsonObject.get("nickName").toString(), "");
            minUserInfo.setNickName(aa);
        }
        if (jsonObject.get("avatarUrl") != null) {
            minUserInfo.setPhotoUrl(jsonObject.get("avatarUrl").toString());
        }
        if (jsonObject.get("gender") != null) {
            minUserInfo.setSex(jsonObject.get("gender").toString());
        }
        if (jsonObject.get("phoneNumber") != null) {
            minUserInfo.setPhone(jsonObject.get("phoneNumber").toString());
            //如果保存手机号，并且推荐人信息不为空，增加推荐记录
        }
        //处理最后浏览店铺
        List<Shopping> shoppings = shoppingRepository.findAllByMiniUserIdAndDelFlag(miniUserId, "0");
        if (shoppings.size() > 0) {

        }
        minUserInfo.setModifyTime(new Date());
        minUserInfoRepository.saveAndFlush(minUserInfo);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("获取成功");
        apiResultBean.setData(minUserInfo);

        return apiResultBean;
    }

    /**
     * emoji表情替换
     *
     * @param source
     * @param slipStr
     * @return
     */
    private String filterEmoji(String source, String slipStr) {
        if (StringUtils.isNotBlank(source)) {
            return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", slipStr);
        } else {
            return source;
        }
    }

    /**
     * 获取unionId,并保存用户信息
     *
     * @param
     * @return
     */
    @RequestMapping(value = "saveUserPhone", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean saveUserPhone(String miniUserId, String sessionKey, String encryptedData, String iv) {
        ApiResultBean apiResultBean = new ApiResultBean();


        if (StringUtil.isEmpty(miniUserId) || StringUtil.isEmpty(encryptedData) || StringUtil.isEmpty(sessionKey) || StringUtil.isEmpty(iv)) {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("请求失败！miniUserId为空！");
            return apiResultBean;
        }

        WXBizDataCrypt biz = new WXBizDataCrypt(WechatMiniConfig.MINI_APP_ID, sessionKey);
        String returnInfo = biz.decryptData(encryptedData, iv);
        JSONObject object = JSONObject.fromObject(returnInfo);
        String userinfo = object.get("userInfo").toString();
        JSONObject jsonObject = JSONObject.fromObject(userinfo);
        MinShoppingUserInfo minUserInfo = minUserInfoRepository.findOne(miniUserId);


        if (jsonObject.get("phoneNumber") != null) {
            String phone = this.filterEmoji(jsonObject.get("phoneNumber").toString(), "");
            minUserInfo.setPhone(phone);
            List<Shopping> shoppings = shoppingRepository.findAllByPhoneAndDelFlag(phone, "0");
            if (shoppings.size() > 0) {
                minUserInfo.setPhone(phone);
                minUserInfo.setIsGuide("1");
                minUserInfo.setShoppingId(shoppings.get(0).getId());
            } else {
                minUserInfo.setPhone(phone);
                minUserInfo.setIsGuide("0");
            }
        } else {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("接口错误");
            return apiResultBean;
        }

        minUserInfo.setModifyTime(new Date());
        minUserInfoRepository.saveAndFlush(minUserInfo);
        apiResultBean.setCode(ApiResultBean.SUCCESS);
        apiResultBean.setMsg("获取成功");
        apiResultBean.setData(minUserInfo);

        return apiResultBean;
    }

    /**
     * 查看所属店铺所有赠品所有赠品
     *
     * @param shoppingId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/queryAllGoods", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryAllGoods(String shoppingId, AntPage antPage) {
        return shoppingService.queryAllGoods(shoppingId, antPage);
    }

    /**
     * 查看附近店铺
     *
     * @param longitude
     * @param latitude
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/queryNearbyShop", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryNearbyShop(String longitude, String latitude, String miniUserId, String shopName, AntPage antPage) {
        return shoppingService.queryNearbyShop(longitude, latitude, miniUserId, shopName, antPage);
    }

    /**
     * 查看导购赠品记录
     *
     * @param shoppingId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/queryUserLog", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryUserLog(String shoppingId, AntPage antPage) {
        return shoppingService.queryUserLog(shoppingId, antPage);
    }

    /**
     * 查看用户领取详情
     *
     * @param userOpenid
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/userHistoryLog", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean userHistoryLog(String userOpenid, AntPage antPage) {
        return shoppingService.userHistoryLog(userOpenid, antPage);
    }

    /**
     * 申请成为导购
     *
     * @param miniUserId
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/shoppingApply", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean shoppingApply(String miniUserId, String shopId, String isPerpetual, String startTime, String endTime) {
        String minUserId = miniUserId;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = null;
        Date end = null;
        try {
            start = sdf.parse(startTime);
            end = sdf.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return shoppingService.shoppingApply(minUserId, shopId, isPerpetual, start, end);

    }

    /**
     * 用户查看个人申请
     *
     * @param miniUserId
     * @return
     */
    @RequestMapping(value = "/queryApply", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryApply(String miniUserId) {
        String minUserId = miniUserId;
        return shoppingService.queryApply(minUserId);
    }

    /**
     * 查看赠品领取记录
     *
     * @param goodsId
     * @param shoppingId
     * @param antPage
     * @return
     */
    @RequestMapping(value = "/queryGoodsGetLog", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean queryGoodsGetLog(String goodsId, String shoppingId, String shopId, AntPage antPage, String startTime, String endTime) {


        return shoppingService.queryGoodsGetLog(goodsId, shoppingId, shopId, antPage, startTime, endTime);
    }

    /**
     * 取消申请
     *
     * @param miniUserId
     * @return
     */
    @RequestMapping(value = "/cancelApply", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean cancelApply(String miniUserId) {
        return shoppingService.cancelApply(miniUserId);
    }

    /**
     * 赠品详情
     *
     * @param shoppingId
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/goodsDetails", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean goodsDetails(String shoppingId, String goodsId) {
        return shoppingService.goodsDetails(shoppingId, goodsId);
    }

    /**
     * 查看导购历史门店
     *
     * @param shoppingId
     * @return
     */
    @RequestMapping(value = "/miniQueryHistoryShop", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean miniQueryHistoryShop(String shoppingId) {
        return shoppingService.miniQueryHistoryShop(shoppingId);
    }

    /**
     * 导购统计
     *
     * @param shoppingId
     * @param antPage
     * @param shopId
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "/shoppingStatistics", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean shoppingStatistics(String shoppingId, AntPage antPage, String shopId, String startTime, String endTime) {
        return shoppingService.shoppingStatistics(shoppingId, antPage, shopId, startTime, endTime);
    }

    /**
     * 导购生成二维码
     *
     * @return
     */

    @RequestMapping(value = "/getCode", method = RequestMethod.POST)
    @ResponseBody
    public ApiResultBean getCode(String shoppingId, String goodsId) {
        return  shoppingService.getCode(shoppingId,goodsId);
    }



}